import 'package:flutter/material.dart';
import 'package:flutter_douban/config/Http_service.dart';
import 'package:flutter_douban/config/app_colors.dart';
import 'package:flutter_douban/loading/custom_footer.dart';
import 'package:flutter_douban/loading/custom_header.dart';
import 'package:flutter_douban/main_page/home/recommend/cook_recomend_view.dart';
import 'package:flutter_douban/model/banner_model.dart';
import 'package:flutter_douban/model/cook_info_model.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';

class HomeVideoPage extends StatefulWidget {
  const HomeVideoPage({Key? key}) : super(key: key);

  @override
  _HomeVideoPageState createState() => _HomeVideoPageState();
}

class _HomeVideoPageState extends State<HomeVideoPage>
    with AutomaticKeepAliveClientMixin {
  /// 下拉刷新控制器
  EasyRefreshController? _easyRefreshController;

  /// 独立的滚动视图 防止tab切换时触发下拉刷新
  ScrollController? _scrollController;

  /// 列表数组模型
  List<CookInfoModel> _cookInfoList = CookInfoModelList([]).list;
  int page = 0;
  int limit = 10;
  bool hasMore = true;
  bool loading = true;
  bool error = false;
  String? errorMsg;

  // 获取数据
  Future _getRecommendData({bool replace = true}) async {
    try {
      /// 全部数据
      Map<String, dynamic> result =
          await HttpService.getHomeVideoData(page: page, pageSize: 10);
      /// 列表数据
      List list = [];
      for (Map item in result['list']) {
        list.add(item['r']);
      }
      CookInfoModelList infoList = CookInfoModelList.fromJson(list);
      setState(() {
        page++;
        if (replace) {
          _cookInfoList = infoList.list;
        } else {
          _cookInfoList.addAll(infoList.list);
        }
      });
    } catch (e) {
      setState(() {
        error = true;
        errorMsg = e.toString();
      });
    } finally {
      setState(() {
        loading = false;
      });
    }
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _easyRefreshController = EasyRefreshController();
    _scrollController = ScrollController();
  }

  @override
  void dispose() {
    _easyRefreshController!.dispose();
    _scrollController!.dispose();
    super.dispose();
  }

  // 刷新回调(null为不开启刷新)
  Future _onRefresh() async {
    if (error) {
      setState(() => error = false);
    }
    page = 0;
    await _getRecommendData();
    // 恢复刷新状态 使onLoad再次可用
    _easyRefreshController!.resetLoadState();
  }

  // 加载回调(null为不开启加载)
  Future _onLoad() async {
    if (hasMore) {
      await _getRecommendData(replace: false);
    }
    // 结束加载
    _easyRefreshController!.finishLoad(noMore: !hasMore);
  }

  @override
  Widget build(BuildContext context) {
    return EasyRefresh(
      // 开启首次加载刷新
      firstRefresh: true,
      // 加载时的loading
      // firstRefreshWidget: PageFeedBack(firstRefresh: true).build(),
      // 空视图、异常视图
      // emptyWidget: PageFeedBack(
      //   loading: loading,
      //   error: error,
      //   empty: _songList.isEmpty,
      //   errorMsg: errorMsg,
      //   onErrorTap: () => _easyRefreshController.callRefresh(),
      //   onEmptyTap: () => _easyRefreshController.callRefresh(),
      // ).build(),
      header: CustomHeaderView(),
      footer: CustomFooterView(),
      controller: _easyRefreshController,
      enableControlFinishRefresh: false,
      enableControlFinishLoad: true,
      onRefresh: _onRefresh,
      onLoad: _onLoad,
      child: ListView.builder(
          controller: _scrollController,
          itemCount: _cookInfoList.length,
          shrinkWrap: true, //增加
          itemBuilder: (BuildContext context, int index) {
            return CooKRecommendView(
              model: _cookInfoList[index],
            );
          }),
    );
  }

  @override
  bool get wantKeepAlive => true;
}
